package com.jlboot.core.util;

import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wangsanfei
 * @version 1.0
 * Create by 2024/2/29 14:44
 */
@Slf4j
public class CacheUtil {


    public static void put(String cacheName, Object key, Object value) {
        CacheKit.put(cacheName,key,value);
    }

    public static <T> T get(String cacheName, Object key) {
        log.info("命中缓存:{},{}",cacheName,key);
        return CacheKit.get(cacheName,key);
    }

    public static void remove(String cacheName, Object key) {
        CacheKit.remove(cacheName,key);
    }

    public static void removeAll(String cacheName) {
        CacheKit.removeAll(cacheName);
    }

    public static <T> T get(String cacheName, Object key, IDataLoader dataLoader) {
        return CacheKit.get(cacheName,key,dataLoader);
    }

    public static <T> T get(String cacheName, Object key, Class<? extends IDataLoader> dataLoaderClass) {
        return CacheKit.get(cacheName,key,dataLoaderClass);
    }

    public static String[] getCacheNames(){
        return CacheKit.getCacheManager().getCacheNames();
    }

    public static Cache getCache(String cacheName){
        net.sf.ehcache.Cache ecache=CacheKit.getCacheManager().getCache(cacheName);
        Cache cache=new Cache();
        cache.setName(ecache.getName());
        cache.setMaxElementsInMemory(cache.getMaxElementsInMemory());
        cache.setEternal(cache.isEternal());
        cache.setTimeToLiveSeconds(cache.timeToLiveSeconds);
        cache.setTimeToIdleSeconds(cache.timeToIdleSeconds);
        return cache;
    }

    @Data
    public static class Cache{
        /**
         * 缓存名称
         */
        private String name;
        /**
         * 最大内存数量
         */
        private int maxElementsInMemory;
        /**
         * 是否永久的
         */
        private boolean eternal;
        /**
         * 存活时间
         */
        private long timeToLiveSeconds;
        /**
         * 最后一次访问或修改时间
         */
        private long timeToIdleSeconds;

    }

}
